import { defineStore } from "pinia";
import { h, ref, type Component } from "vue";
import { nextTick } from "vue";
import api from '@/api'
import { currentNodeInfo } from "./currentNodeStore";
import { loadHeadings } from "@/components/index-left/index-dagang/dagang";
import { useUserStore } from "./userStore";
import { createTiptapMarkdownParser } from "@/tiptap/extensions/tiptapMarkdownParser";
//**
// 文档对象管理库
//  */
export const useEditorStore = defineStore(
  "editor",
  () => {
    const aiCurrentMsg = ref("你好")
    const selection = ref() //记录当前选中
    const isUpdate = ref(false)
    const title = ref("当前编辑器标题");
    //所有标头
    const headings = ref();
    //当前激活的标头 点击后的
    const activeHeading = ref();
    // 编辑器实例
    const editorInstance = ref();
    // 编辑器内容 html
    const editorContent = ref("<p> 你好我是pinia库里的初始化 查找editorStore </p>");
    const nodeId = ref();
    const editorMarkdown = ref()
    const setHeadings = (data: any) => {
      headings.value = data;
    };
    /**
     * 大纲定位滚动方法
     */
    const setActiveHeading = (data: any) => {
      activeHeading.value = data; //保存当前标签
      console.log("activeHeading", activeHeading.value);
      // 使用文字的偏移字符数来获取Node节点
      //   const node = editorInstance.value?.state.doc.nodeAt(data.start)

      // 找到Node节点在所对应的DOM节点
      const dom = editorInstance.value.view.domAtPos(data.start + 1).node;
      // 回滚到dom节点
      dom.scrollIntoView({ behavior: "smooth", block: "start" });
    };
    //取html 标签
    const getHtml = () => {
      return editorContent.value;
    };
    //获取标题

    //获取文档真实内容
    const getText = () => {
      return editorInstance.value.getText();
    };
    //获取标题
    const getTitle = ()=>{
      return title.value;
    }
    //取编辑器对象
    const getEditor =()=>{
      return editorInstance;
    }
    //取mark内容
    const getMarkdown =()=>{
      return editorMarkdown.value
    }

    //实时同步标签内容
    const setEditorContent = (data: string) => {
      editorContent.value = data;
      console.log(editorContent.value);
    };
    //同步当前 编辑器对象 并且存储上下文
    const setEditor = (editor:any,html:any)=>{
        const nodeInfo = currentNodeInfo()
        editorContent.value = html
        editorInstance.value = editor
        nodeInfo.nodeMarkdown = editor.storage.markdown.getMarkdown();
        nodeInfo.nodehtml = editor.getHTML()
        nodeInfo.nodeText = editor.getText()
        nodeInfo.isUpdate = true
    }
   // 同步实例对象
    const setEditorInstance = (data: any) => {
      editorInstance.value = data;
    };
    //设置文档id
    const setNodeId = (data: any) => {
      nodeId.value = data;
    };
    // 更新标题
    const setTitle = (data: string) => {
      title.value = data;
    };
    // 给编辑器传markdown内容
    const setEditorForMarkDown = (data:string)=>{
      editorInstance.value.commands.setContent(data)
    }
    //插入内容 在光标后插入
    const insertContext = (data:any)=>{
      console.log("即将插入",data)
        const parser = createTiptapMarkdownParser(editorInstance.value.schema)
            // const cleaned = cleanFenceWrap(lastSuggestion)
          try{
            const docNode = parser.parse(data)
            const content = docNode.content
            if (content.childCount === 0) {
              console.warn('AI 返回内容为空，无法插入')
              return true
            }
            // 用 Tiptap 的智能命令插入整个 JSON 结构

            editorInstance.value.commands.insertContent(docNode.toJSON())
          } catch (err)
          {
            console.warn('Markdown 插入失败:', err)
          }

    // editorInstance.value?.commands.insertContent(data);
    }



    // 保存该文档 到数据库

    //更新当前页面信息
    const getCurrentNode = (data:string)=>{
     const cnodeInfo =  currentNodeInfo()
     const userStore = useUserStore()
     if (cnodeInfo.isUpdate && userStore.user.role == 0) {
       if(confirm("你之前文件做了修改是否保存文件")){
        console.log("保存当前文档",cnodeInfo)
        cnodeInfo.save()
       }
     }
     api.nodeInfo.getNodeById(data)
      .then((res:any)=>{
         if(res.code ==200){
          //修改节点信息
         cnodeInfo.updateCurrentEditorState(res.data)
         loadHeadings()
         }
      })
      .catch(error=>{
         console.log(error)
      })
    }

    return {
      title,
      headings,
      activeHeading,
      editorContent,
      nodeId,
      setHeadings,
      setTitle,
      setActiveHeading,
      editorInstance,
      isUpdate,
      setEditorInstance,
      setEditorContent,
      getHtml,
      setNodeId,
      setEditor,
      getCurrentNode,
      getEditor,
      getMarkdown,
      setEditorForMarkDown,
      getText,
      insertContext,
      selection
    };
  },

);
